package com.unieagle.exam.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;
import com.unieagle.exam.db.DatabaseContext;
import com.unieagle.exam.db.ExamDBHelper;
import com.unieagle.exam.model.Subject;
import com.unieagle.exam.utils.SharedPreferenceUtils;

/**
 * 工种选择
 * @author QianJing
 *
 */
public class SubjectChooseActivity extends BaseActivity{
	
	private List<Subject> subjects;
	
	private ListView mListView;
	
	private SubjectAdapter mAdapter;
	
	private long firstTime = 0;
	
	private BroadcastReceiver mReceiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.subject_choose_activity_layout);
		init();
	}
	
	protected void init() {
		super.init();
		mTvTitle.setText(R.string.subject1);
		if(getIntent().getBooleanExtra("from_add_activity", false)) {
			mBBBack.setVisibility(View.VISIBLE);
		} else {
			mBBBack.setVisibility(View.GONE);
			mTvRight.setBackgroundResource(R.drawable.ic_setting);
			mTvRight.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent i = new Intent(SubjectChooseActivity.this, SettingActivity.class);
					startActivity(i);
				}
			});
		}
		mListView = (ListView) findViewById(R.id.list);
		mReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				AccountManager.getInstance().getUserInfo().setActivation_status("activation_active");
				AccountManager.getInstance().updateUserInfoResult(AccountManager.getInstance().getUserInfo());
				Intent i = new Intent(SubjectChooseActivity.this, AddSubjectActivity.class);
            	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            	i.putExtra("from_splash", true);
            	startActivity(i);
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction("user_activated");
		registerReceiver(mReceiver, filter);
		getSubjects();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mReceiver != null) {
			unregisterReceiver(mReceiver);
			mReceiver = null;
		}
	}
	
	private void getSubjects() {
		subjects = new ArrayList<Subject>();
		new GetSubjectsTask().execute();
	}
	
	/**
	 * 获取工种
	 * @author QianJing
	 *
	 */
	class GetSubjectsTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... arg0) {
			ExamDBHelper helper = new ExamDBHelper(new DatabaseContext(SubjectChooseActivity.this));
			subjects = helper.getSubject1();
			if(subjects.size() > 0) {
				return true;
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result) {
				mAdapter = new SubjectAdapter(SubjectChooseActivity.this, subjects);
				mListView.setAdapter(mAdapter);
			}
		}
		
	}
	
	private void startChooseSubject2(int id, String title) { //选择二级科目
		Intent i = new Intent(this, SubjectChoose2Activity.class);
		i.putExtra("title", title);
		i.putExtra("id", id);
		startActivity(i);
	}
	
	class SubjectAdapter extends BaseAdapter {
		
		private List<Subject> subjects;
		
		private LayoutInflater inflator;
		
		public SubjectAdapter(Context ctx, List<Subject> subjects) {
			this.subjects = subjects;
			inflator = LayoutInflater.from(ctx);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return subjects.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return subjects.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflator.inflate(R.layout.subject_choose_activity_listitem, null);
				holder.mTvSubject = (TextView) convertView.findViewById(R.id.subject);
				holder.item = (LinearLayout) convertView.findViewById(R.id.item);
 				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			Subject sub = subjects.get(arg0);
			final int id = (int)sub.getId();
			final String title = sub.getTitle();
			holder.mTvSubject.setText(sub.getTitle());
			convertView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(getIntent().getBooleanExtra("from_add_activity", false)) {
						addSubject(id);
					} else {
						int cnt = SharedPreferenceUtils.getFreeExamCount(SubjectChooseActivity.this);
						if(cnt > 0) { //还剩余试用次数
							startChooseSubject2(id, title);
						} else {
							Toast.makeText(SubjectChooseActivity.this, "5次试用已满，请申请激活", Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			if(title.equals("起重机械作业")) {
				holder.item.setBackgroundResource(R.drawable.lift);
			} else if(title.equals("厂内机动车辆作业")) {
				holder.item.setBackgroundResource(R.drawable.viechle);
			} else if(title.equals("焊工作业")) {
				holder.item.setBackgroundResource(R.drawable.hangong);
			} else if(title.equals("电工作业")) {
				holder.item.setBackgroundResource(R.drawable.ele);
			} else if(title.equals("安全管理人员")) {
				holder.item.setBackgroundResource(R.drawable.safety);
			} else if(title.equals("企业主要负责人")) {
				holder.item.setBackgroundResource(R.drawable.enterprise);
			} else if(title.equals("危险化学品工艺作业")) {
				holder.item.setBackgroundResource(R.drawable.chem);
			} else if(title.equals("高处作业")) {
				holder.item.setBackgroundResource(R.drawable.high);
			} 
			return convertView;
		}
	}
	
	class ViewHolder {
		
		TextView mTvSubject;
		
		LinearLayout item;
	}
	
	private void addSubject(int id) {
		Intent i = new Intent();
		i.putExtra("id", id);
		setResult(RESULT_OK, i);
		finish();
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
            	if(!getIntent().getBooleanExtra("back_flag", false)) {
	                long secondTime = System.currentTimeMillis();
	                if (secondTime - firstTime > 2000)
	                {
	                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
	                    firstTime = secondTime;
	                    return true;
	                }
	                else
	                {
	                    finish();
	                }
            	} else {
            		finish();
            	}
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
}
